import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import store from '@/store'

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 15000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.error(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    
    if (res.code !== 0) {
      ElMessage.error(res.msg || '请求失败')
      
      // token失效
      if (res.code === 401) {
        store.dispatch('user/resetToken').then(() => {
          router.push(`/login?redirect=${router.currentRoute.value.fullPath}`)
        })
      }
      
      return Promise.reject(new Error(res.msg || '请求失败'))
    }
    
    return res
  },
  error => {
    console.error(error)
    ElMessage.error(error.message || '请求失败')
    return Promise.reject(error)
  }
)

export default service 